import math
import subprocess
import sys

from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfgen import canvas
import pandas as pd
from reportlab.platypus import Paragraph

margin = 36  # 假设边距为1英寸（在PDF中，1英寸=72点）

img_width, img_height = 50, 50  # 图片尺寸
img_spacing = 17.5  # 图片之间的间距


def calculate_pos(count):
    pos = []
    width, height = letter

    row_count = 0
    x_pos = margin
    y_pos = height - 130
    print(f'width: {width}, height: {height}\n'
          f'img_spacing: {img_spacing}, margin: {margin}\n'
          f'start_x: {x_pos}, start_y: {y_pos}')
    for i in range(count):
        pos.append((x_pos, y_pos))  # 当前坐标

        if row_count + 1 >= 8:
            row_count = 0
            x_pos = margin
            y_pos = y_pos - img_height - img_spacing
        else:
            row_count += 1
            x_pos += img_width + img_spacing
    return pos


def wrap_text(text, width):
    """
    将文本自动换行，以适应给定的宽度。

    参数:
    text (str): 要换行的原始文本。
    width (int): 换行前的最大宽度（以字符为单位）。

    返回:
    str: 换行后的文本 (list)。
    """
    words = text.split()  # 将文本拆分为单词列表
    wrapped_lines = []  # 用于存储每行的列表
    current_line = []  # 当前正在构建的行

    for word in words:
        # 如果添加当前单词会导致当前行超过宽度限制，则先保存当前行
        if (len(' '.join(current_line + [word])) > width) and current_line:
            wrapped_lines.append(' '.join(current_line))
            current_line = [word]  # 开始新的一行
        else:
            current_line.append(word)

            # 添加最后一行（如果有的话）
    if current_line:
        wrapped_lines.append(' '.join(current_line))

    # return '\n'.join(wrapped_lines)
    return wrapped_lines


class PDF:
    def __init__(self, resource_dir):
        self.resource_dir = resource_dir
        self.excel_file_path = resource_dir + '/Process_Definition.csv'
        self.image_dir_path = resource_dir + '/image'
        self.target_file_path = resource_dir + '/process_flow.pdf'
        self.pdf = canvas.Canvas(self.target_file_path, pagesize=letter)
        self.process_define_df = None
        self.pos = None

    def parse_excel_file(self):
        self.process_define_df = pd.read_csv(self.excel_file_path)
        self.pos = calculate_pos(self.process_define_df.shape[0])

    def parse_image_dir(self):
        command = 'ls ' + self.image_dir_path
        result = subprocess.run(command, shell=True, text=True, capture_output=True)
        pics = result.stdout.strip().split('\n')
        if len(pics) < self.process_define_df.shape[0]:
            raise Exception('图片数量小于流程定义数量')

    def pdf_add_pic(self):
        for index, row in self.process_define_df.iterrows():
            cur_pos = self.pos[index]
            pic_name = f'{row["Line number"]}-{row["Station number"]}.png'
            self.pdf.drawImage(self.image_dir_path + '/' + pic_name, cur_pos[0], cur_pos[1], width=50, height=50,
                               preserveAspectRatio=True)

    def pdf_add_text(self):
        for index, row in self.process_define_df.iterrows():
            cur_pos = self.pos[index]
            text = f'{row["Line number"]}-{row["Station number"]}. {row["Station Name"]}'
            wrapped_text = wrap_text(text, 18)
            self.pdf.setFont("Helvetica", 5)
            x_pos, y_pos = cur_pos[0] + img_width / 2, cur_pos[1] + img_height + 1
            for txt in wrapped_text:
                # self.pdf.drawString(cur_pos[0], cur_pos[1], wrapped_text)
                self.pdf.drawCentredString(x_pos, y_pos, txt)
                y_pos -= 5

    def pdf_add_DL_cir(self):
        for index, row in self.process_define_df.iterrows():
            cur_pos = self.pos[index]
            dl = row["DL"]
            self.pdf.setStrokeColorRGB(135/255, 206/255, 235/255)  # 135 206 235
            self.pdf.setLineWidth(0.5)
            self.pdf.circle(cur_pos[0]+4.3, cur_pos[1]+4, 3, stroke=1, fill=0)
            self.pdf.setFont("Helvetica", 4)
            self.pdf.drawCentredString(cur_pos[0]+4.3, cur_pos[1]+2.5, str(dl))

    def pdf_add_QPL_rect(self):
        for index, row in self.process_define_df.iterrows():
            cur_pos = self.pos[index]
            qpl = row["QPL"]
            ng_box = row["NG box"]
            if ng_box == 'yes':
                self.pdf.setStrokeColorRGB(1, 0, 0)
            else:
                self.pdf.setStrokeColorRGB(135 / 255, 206 / 255, 235 / 255)  # 135 206 235
            self.pdf.setLineWidth(0.5)
            # self.pdf.circle(cur_pos[0] + img_width - 4.5, cur_pos[1] + 4, 3, stroke=1, fill=0)
            self.pdf.setFont("Helvetica", 4)
            self.pdf.drawCentredString(cur_pos[0] + img_width - 4.5, cur_pos[1] + 2.5, str(qpl))
            self.pdf.roundRect(cur_pos[0] + img_width - 7, cur_pos[1]+1.1, 6, 6, 1, stroke=1, fill=0)

    def pdf_add_arrow(self):
        for index, row in self.process_define_df.iterrows():
            if index == self.process_define_df.shape[0]-1:  # 最后一个不加箭头
                break
            cur_pos = self.pos[index]
            start_x, start_y, end_x, end_y = (cur_pos[0]+img_width+1, cur_pos[1]+img_height/2,
                                              cur_pos[0]+img_width+8.75, cur_pos[1]+img_width/2)
            self.pdf.setStrokeColorRGB(0, 0, 0)
            self.pdf.setLineWidth(2)
            self.pdf.line(start_x, start_y, end_x, end_y)

            # 手搓一个三角形！！！
            pos_a = [end_x, end_y+2]
            pos_b = [end_x+8, end_y]
            pos_c = [end_x, end_y-2]
            self.pdf.setLineWidth(0.5)
            self.pdf.line(pos_a[0], pos_a[1], pos_b[0], pos_b[1])  # AB
            self.pdf.line(pos_b[0], pos_b[1], pos_c[0], pos_c[1])  # BC
            self.pdf.line(pos_a[0], pos_a[1], pos_c[0], pos_c[1])  # AC

    def pad_add_out_rect(self):
        self.pdf.setLineWidth(1)
        for index, row in self.process_define_df.iterrows():
            cur_pos = self.pos[index]
            station_type = row['Station Type']
            if station_type == 'Auto-assembly':
                self.pdf.setStrokeColorRGB(0.12, 0.56, 1)
            elif station_type == 'Semi-auto':
                self.pdf.setStrokeColorRGB(0.67, 0.51, 1)
            elif station_type == 'Manual-assembly':
                self.pdf.setStrokeColorRGB(0.47, 0.53, 0.6)
            elif station_type == 'Inspection':
                self.pdf.setStrokeColorRGB(1, 0.92, 0.55)
            elif station_type == 'Func-Tester':
                self.pdf.setStrokeColorRGB(124/255, 205/255, 124/255)
            else:
                raise Exception(f'未知的站位类型:{station_type}')
            self.pdf.roundRect(cur_pos[0], cur_pos[1], img_width, img_height + 6, 3, stroke=1, fill=0)

    def pdf_add_others(self):
        line_name = self.process_define_df['Line Name'][0]
        self.pdf.setFont("Helvetica", 10)
        self.pdf.drawString(47, 745, f"{line_name} (process flow)")

        rec_width, rec_height = 35, 12
        color_def_pos = [520 - (rec_width+5)*4,
                         520 - (rec_width+5)*3,
                         520 - (rec_width+5)*2,
                         520 - (rec_width+5),
                         520]
        self.pdf.setFillColorRGB(0.12, 0.56, 1)
        self.pdf.setFont("Helvetica", 5)
        self.pdf.roundRect(color_def_pos[0], 742, rec_width, rec_height, 3, stroke=0, fill=1)
        self.pdf.setFillColorRGB(0, 0, 0)  # 黑色文字
        self.pdf.drawCentredString(color_def_pos[0]+rec_width/2, 746.5, 'Auto-assy')

        self.pdf.setFillColorRGB(0.67, 0.51, 1)
        self.pdf.setFont("Helvetica", 5)
        self.pdf.roundRect(color_def_pos[1], 742, rec_width, rec_height, 3, stroke=0, fill=1)
        self.pdf.setFillColorRGB(0, 0, 0)  # 黑色文字
        self.pdf.drawCentredString(color_def_pos[1]+rec_width/2, 746.5, 'Semi-auto')

        self.pdf.setFillColorRGB(0.47, 0.53, 0.6)
        self.pdf.setFont("Helvetica", 5)
        self.pdf.roundRect(color_def_pos[2], 742, rec_width, rec_height, 3, stroke=0, fill=1)
        self.pdf.setFillColorRGB(0, 0, 0)  # 黑色文字
        self.pdf.drawCentredString(color_def_pos[2]+rec_width/2, 746.5, 'Manual-assy')

        self.pdf.setFillColorRGB(1, 0.92, 0.55)
        self.pdf.setFont("Helvetica", 5)
        self.pdf.roundRect(color_def_pos[3], 742, rec_width, rec_height, 3, stroke=0, fill=1)
        self.pdf.setFillColorRGB(0, 0, 0)  # 黑色文字
        self.pdf.drawCentredString(color_def_pos[3]+rec_width/2, 746.5, 'Inspection')

        self.pdf.setFillColorRGB(124/255, 205/255, 124/255)
        self.pdf.setFont("Helvetica", 4)
        self.pdf.roundRect(color_def_pos[4], 742, rec_width, rec_height, 3, stroke=0, fill=1)
        self.pdf.setFillColorRGB(0, 0, 0)  # 黑色文字
        self.pdf.drawCentredString(color_def_pos[4]+rec_width/2, 746.5, 'Func-test')

    def pdf_add_border(self):
        count = self.process_define_df.shape[0]
        width, height = letter
        row_count = math.ceil(count/8)
        h = (row_count + 1) * (img_height + img_spacing)
        self.pdf.setStrokeColorRGB(0, 0, 0)
        self.pdf.setLineWidth(1)
        self.pdf.rect(15, height-h-15, width-30, h, 1, fill=0)

    def pdf_save(self):
        self.pdf.save()


if __name__ == '__main__':
    print(4/3)
    print(math.ceil(56/9))
    # print(4/3)
    # pdf = PDF('/Users/sanghaobo/Desktop')
    # pdf.parse_excel_file()
